package com.velvetantler.weather.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.qweather.sdk.response.weather.WeatherHourly
import com.velvetantler.weather.R
import com.velvetantler.weather.utils.WeatherUtils

class WeatherHourlyItemAdapter(private val data: List<WeatherHourly>) :
    RecyclerView.Adapter<WeatherHourlyItemAdapter.ViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_hour_weather, parent, false)
        )
    }

    @SuppressLint("SetTextI18n", "UseCompatLoadingForDrawables")
    override fun onBindViewHolder(
        holder: ViewHolder,
        position: Int
    ) {
        val item = data[position]
        holder.view.apply {
            findViewById<TextView>(R.id.tv_hour).text = WeatherUtils.isoTo24HourTime(item.fxTime)
            findViewById<TextView>(R.id.tv_hour_temp).text = item.temp + "°"
            findViewById<TextView>(R.id.tv_hour_humidity).text = "湿度 ${item.humidity}%"
            findViewById<TextView>(R.id.tv_hour_wind).text = "${item.windDir} ${item.windScale}级"
            findViewById<TextView>(R.id.tv_hour_pressure).text = "${item.pressure} hPa"
            // 设置天气图标
            val iconCode = "_${item.icon.replace("-", "_")}"
            val iconId = context.resources.getIdentifier(iconCode, "drawable", context.packageName)
            if (iconId != 0) {
                context.resources.getDrawable(iconId, null)?.let {
                    findViewById<ImageView>(R.id.iv_hour_weather).setImageDrawable(it)
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val view = itemView.findViewById<View>(R.id.item_hour_weather)
    }

}